package logic

import (
	"context"
	"errors"
	"video-manager/model/cache"
	"video-manager/model/mysql"
	"video-manager/pkg"

	"video-manager/usersrpc/internal/svc"
	"video-manager/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *usersrpc.LoginRequest) (*usersrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User

	err := findUser.FindUserByPhoneNum(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("账号不存在")
	}
	if in.LoginType == 1 {
		if findUser.Pwd != pkg.MD5(in.PassWord) {
			return nil, errors.New("密码错误，请重新登录")
		}
	} else if in.LoginType == 2 {
		result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
		if result != in.SmsCode {
			return nil, errors.New("验证码错误，请重新登录")
		}
	} else {
		return nil, errors.New("请选择登录类型")
	}
	if findUser.Account_status == 1 {
		return nil, errors.New("账号禁用处于禁用状态")

	}
	return &usersrpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
